module Pagination
  module Generators
    #bin/rails g pagination:views
    #bin/rails g pagination:views --views-prefix admin
    class ViewsGenerator < Rails::Generators::Base #Rails::Generators::NamedBase
      #指定views source的目录
      source_root File.expand_path('../../../../app/views/pagination', __FILE__)

      #命令参数 --views-prefix XXX
      class_option :views_prefix, type: :string, desc: '存放view路径的前缀'

      def copy_view_files
        # pp file_name,options[:views_prefix]
        # 筛选文件
        filename_pattern = File.join(self.class.source_root, '*.html.erb')
        Dir.glob(filename_pattern).each do |f|
          file = File.basename(f)
          copy_file file, view_path_for(file) #复制文件
        end
      end

      private
      #路径前缀
      def views_prefix
        options[:views_prefix].try(:to_s)
      end

      #目标路径
      def view_path_for(file)
        ['app', 'views', views_prefix, 'pagination', File.basename(file)].compact.join('/')
      end
    end
  end
end